//
//  WebsiteViewController.m
//  BaoVn
//
//  Created by Le Anh Tai on 11/17/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "WebsiteViewController.h"
#import "OneNewsItemView.h"
#import "VLDContextSheetItem.h"
#import <Twitter/Twitter.h>
#import <Social/Social.h>
#import <MessageUI/MessageUI.h>

#define BACKWARD_OPTION @"Trang trước"
#define FORWARD_OPTION @"Trang sau"
#define TWITTER_OPTION @"Chia sẻ twitter"
#define FACEBOOK_OPTION @"Chia sẻ facebook"
#define EMAIL_OPTION @"Gửi email"
#define SMS_OPTION @"Gửi sms"

@interface UIAlertView (Blocker)
@end

// Do not show alert
@implementation UIAlertView (Blocker)
- (void)show
{
    return;
}
@end

@interface WebsiteViewController ()<MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate>

@end

@implementation WebsiteViewController

- (instancetype)init
{
    if (self = [super init])
    {
        _newsItemView = [[OneNewsItemView alloc] init];
        _newsItemView.delegate = self;
        [_contentView addSubview:_newsItemView];
    }
    
    return self;
}

- (void)createContextSheet
{
    if (_contextSheet)
    {
        _contextSheet = nil;
    }
    
    if ([self hasCurrentUrl] == NO)
    {
        return;
    }
    
    //        VLDContextSheetItem *item1 = [[VLDContextSheetItem alloc] initWithTitle:BACKWARD_OPTION
    //                                                                          image:[UIImage imageNamed: @"backward_context_icon"]
    //                                                               highlightedImage:[UIImage imageNamed: @"backward_context_icon"]];
    //
    //        VLDContextSheetItem *item2 = [[VLDContextSheetItem alloc] initWithTitle:FORWARD_OPTION
    //                                                                          image:[UIImage imageNamed: @"forward_context_icon"]
    //                                                               highlightedImage:[UIImage imageNamed: @"forward_context_icon"]];
    
    VLDContextSheetItem *item3 = [[VLDContextSheetItem alloc] initWithTitle:TWITTER_OPTION
                                                                      image:[UIImage imageNamed: @"twitter_context_icon"]
                                                           highlightedImage:[UIImage imageNamed: @"twitter_context_icon"]];
    
    VLDContextSheetItem *item4 = [[VLDContextSheetItem alloc] initWithTitle:FACEBOOK_OPTION
                                                                      image:[UIImage imageNamed: @"facebook_context_icon"]
                                                           highlightedImage:[UIImage imageNamed: @"facebook_context_icon"]];
    
    VLDContextSheetItem *item5 = [[VLDContextSheetItem alloc] initWithTitle:EMAIL_OPTION
                                                                      image:[UIImage imageNamed: @"email_context_icon"]
                                                           highlightedImage:[UIImage imageNamed: @"email_context_icon"]];
    
    
    VLDContextSheetItem *item6 = [[VLDContextSheetItem alloc] initWithTitle:SMS_OPTION
                                                                      image:[UIImage imageNamed: @"sms_context_icon"]
                                                           highlightedImage:[UIImage imageNamed: @"sms_context_icon"]];
    
    _contextSheet = [[VLDContextSheet alloc] initWithItems: @[ item6, item5, item4, item3/*, item2, item1*/ ]];
    _contextSheet.delegate = self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UISwipeGestureRecognizer *rightSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];
    rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:rightSwipeGesture];
    
    // Actions: backward, forward, share facebook, share twitter
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
    longPress.numberOfTouchesRequired = 1;
    longPress.cancelsTouchesInView = YES;
    longPress.delegate = self;
    [self.view addGestureRecognizer:longPress];
    
    if (self.navigationController.childViewControllers.count > 1)
    {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSNumber *isShowGuide = [userDefault objectForKey:@"isShowGuide"];
        if (isShowGuide == nil || [isShowGuide boolValue] == NO)
        {
            [self showGuildeView];
            
            [userDefault setObject:[NSNumber numberWithBool:YES] forKey:@"isShowGuide"];
        }
    }
    
    // Go head of website or webpage if tapping on header
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                   action:@selector(tapHandler:)];

    tapGesture.numberOfTapsRequired = 1;
    tapGesture.cancelsTouchesInView = YES;
    tapGesture.delegate = self;
    [self.view addGestureRecognizer:tapGesture];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]])
    {
        CGPoint point = [gestureRecognizer locationInView:self.view];
        
        CGRect rectHeader = RECT(0, 0, self.view.width, MIN(self.view.height, 30));
        
        if ( CGRectContainsPoint(rectHeader, point) )
        {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    else if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
    {
        return YES;
    }
    
    return NO;//[super gestureRecognizerShouldBegin:gestureRecognizer];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)tapHandler:(UITapGestureRecognizer *)gesture
{
    if ([gesture state] == UIGestureRecognizerStateEnded)
    {
        CGPoint point = [gesture locationInView:self.view];
        
        CGRect rectHeader = RECT(0, 0, self.view.width, MIN(self.view.height, 30));

        if ( CGRectContainsPoint(rectHeader, point) )
        {
            [_newsItemView.webView.scrollView setContentOffset:CGPointMake(_newsItemView.webView.scrollView.contentOffset.x, 0)];
        }
    }
}

- (void)longPressed:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        [self createContextSheet];
        
        if (_contextSheet)
        {
            [_contextSheet startWithGestureRecognizer:gesture inView:self.view];
        }
    }
}

- (void)contextSheet:(VLDContextSheet *)contextSheet didSelectItem:(VLDContextSheetItem *)item
{
    if (item)
    {
        NSString *selectedOption = item.title;
        
        if ([selectedOption isEqualToString:BACKWARD_OPTION])
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else if ([selectedOption isEqualToString:FACEBOOK_OPTION])
        {
            [self shareFacebook];
        }
        else if ([selectedOption isEqualToString:TWITTER_OPTION])
        {
            [self shareTwitter];
        }
        else if ([selectedOption isEqualToString:EMAIL_OPTION])
        {
            [self sendEmail];
        }
        else if ([selectedOption isEqualToString:SMS_OPTION])
        {
            [self sendSMS];
        }
    }
    
//    [contextSheet end];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    navigationBar.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    _guideView.frame = _contentView.bounds;
    
    if (_adsView.superview == nil)
    {
        _newsItemView.frame = _contentView.bounds;
    }
    else
    {
        _adsView.bottom = _contentView.height;
        _adsView.centerX = _contentView.width/2;
        
        _newsItemView.frame = RECT(0, 0, _contentView.width, _contentView.height - _adsView.height);
    }
}

- (void)addAds:(UIView *)adsView
{
    if (_adsView)
    {
        [_adsView removeFromSuperview];
    }
    
    _adsView = adsView;
    [self.view addSubview:_adsView];
    
    _newsItemView.frame = RECT(0, 0, _contentView.width, _contentView.height - _adsView.height);
    _adsView.bottom = _contentView.height;
    _adsView.centerX = _contentView.width/2;
}

- (NSString *)url
{
    return _newsItemView.url;
}

- (void)setUrl:(NSString *)url
{
    _newsItemView.url = url;
}

- (void)loadUrl:(NSString *)url
{
    _finishFirstLoad = NO;
    _rootUrl = url;
    
    [self.navigationController popToRootViewControllerAnimated:NO];
    
//    [self removeNewsController];

    [_newsItemView loadUrl:url];
}

//- (void)showNewsController:(NSString *)url
//{
//    if (_newController)
//    {
//        return;
//    }
//    
//    _newController = [[NewsViewController alloc] init];
//    _newController.delegate = self;
//    [_newController loadUrl:url];
//    [self.navigationController pushViewController:_newController animated:YES];
//}
//
//- (void)removeNewsController
//{
//    if (_newController == nil)
//    {
//        return;
//    }
//    
//    _newController = nil;
//}

- (void)showGuildeView
{
    if (_guideView)
    {
        return;
    }
    
    _guideView = [[GuideSwipeView alloc] init];
    [_guideView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)]];
    [_contentView addSubview:_guideView];
}

- (void)removeGuideView
{
    if (_guideView == nil)
    {
        return;
    }
    
    [_guideView removeFromSuperview];
    _guideView = nil;
}

- (void)tapGestureHandler:(id)sender
{
    [self removeGuideView];
}

#pragma mark - delegate
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(copy:)   ||
        action == @selector(paste:)  ||
        action == @selector(select:) ||
        action == @selector(cut:)    ||
        action == @selector(selectAll:))
    {
        return NO;
    }

    return [super canPerformAction:action withSender:sender];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{

}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    _finishFirstLoad = YES;
}

- (void)updateRedirectURLToMobileWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeOther)
    {
        NSString *newUrl = request.URL.absoluteString;
        
        NSRange range = [_rootUrl rangeOfString:@"//"];
        if (range.location > 0 )
        {
            NSString *oriUrlWithouthttps = [_rootUrl substringFromIndex:(range.location + range.length)];
            if ([newUrl hasSuffix:oriUrlWithouthttps])
            {
                _rootUrl = newUrl;
            }
        }
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = [webView stringByEvaluatingJavaScriptFromString:@"window.location.href"];
    
    if ([url isEqualToString:@"about:blank"] == false)
    {
        _currentUrl = url;
    }
    
    NSString *absoluteUrl = request.URL.absoluteString;
    
    NSLog(@"Should load request: %@", absoluteUrl);
    
    [self updateRedirectURLToMobileWithRequest:request navigationType:navigationType];
    
    if (navigationType == UIWebViewNavigationTypeLinkClicked
        || (_finishFirstLoad && navigationType == UIWebViewNavigationTypeOther && [absoluteUrl hasPrefix:_rootUrl] && [absoluteUrl isEqualToString:_rootUrl] == NO)
        ) {
        WebsiteViewController *controller = [[WebsiteViewController alloc] init];
        [controller loadUrl:absoluteUrl];
        [self.navigationController pushViewController:controller animated:YES];
        
        return NO;
    }
    
    return YES;
}

- (void)newsViewControllerDidPop:(NewsViewController *)controller
{
//    [self removeNewsController];
}

- (void)swipeGestureHandler:(UISwipeGestureRecognizer *)gesture
{
    if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
    {
        if (self.navigationController.childViewControllers.count == 1)
        {
            if ([_newsItemView.webView canGoBack])
            {
                [_newsItemView.webView goBack];
            }
            else
            {
                if ([_delegate respondsToSelector:@selector(websiteRequireShowMenu:)])
                {
                    [_delegate websiteRequireShowMenu:self];
                }
            }
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)shareFacebook
{
    SLComposeViewController *facebookSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
    
    [facebookSheet setInitialText:[NSString stringWithFormat:@"#baovn %@", [_newsItemView getCurrentWebViewTitle]]];
    [facebookSheet addURL:[NSURL URLWithString:_currentUrl]];
    
    [self presentViewController:facebookSheet animated:YES completion:nil];
}

- (void)shareTwitter
{
    SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    [tweetSheet setInitialText:[NSString stringWithFormat:@"#baovn %@", [_newsItemView getCurrentWebViewTitle]]];
    
    [tweetSheet addURL:[NSURL URLWithString:_currentUrl]];
    
    [self presentViewController:tweetSheet animated:YES completion:nil];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendEmail
{
    if ([MFMailComposeViewController canSendMail] == NO)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Lỗi"
                                                        message:@"Vui lòng thiết lặp tài khoản email cho máy bạn"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    
    MFMailComposeViewController *emailController = [[MFMailComposeViewController alloc] init];
    [emailController setSubject:[NSString stringWithFormat:@"[Báo VN] %@", [_newsItemView getCurrentWebViewTitle]]];
    
    NSString *emailBody = _currentUrl;
    [emailController setMessageBody:emailBody isHTML:NO];
    
    emailController.mailComposeDelegate = self;
    [self presentViewController:emailController animated:YES completion:nil];
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendSMS
{
    if ([MFMessageComposeViewController canSendText] == NO)
    {
        return;
    }
    
    MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
    
    smsController.body = [NSString stringWithFormat:@"%@ - %@", [_newsItemView getCurrentWebViewTitle], _currentUrl];
    
    smsController.messageComposeDelegate = self;
    [self presentModalViewController:smsController animated:YES];
}

- (BOOL)hasCurrentUrl
{
    return _currentUrl.length > 0;
}
@end
